<template>

  <!-- 场景配置 -->
  <div class="scenario-configuration">
    <el-dialog
      title="场景配置"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-form ref="form" :model="form" :rules="formRules" label-width="130px">
        <el-form-item label="关联分类:" prop="classifyParentIdPath" >
          <el-cascader
            ref="cascader"
            v-model="form.classifyParentIdPath"
            clearable
            :options="classifyTree"
            :props="{ checkStrictly: true, value: 'id', label: 'classifyName' }"
            @change="classifyParentIdPathChange"
          />
        </el-form-item>
        <el-form-item label="系统名称:" prop="requestSystemId">
          {{ systemName }}
          <!-- <el-select v-model="form.requestSystemId" clearable placeholder="请选择系统名称" @change="requestSystemIdChange">
            <el-option
              v-for="(item, index) in requestSystemIdList"
              :key="index"
              :label="item.systemName"
              :value="item.id"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item label="场景名称:" prop="sceneName">
          <el-input v-model="form.sceneName" clearable :maxlength="50" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="执行模式:" prop="executionMode">
          <el-select v-model="form.executionMode" clearable placeholder="请选择执行模式">
            <el-option
              v-for="(item, index) in dictOptions.executionMode"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.executionMode == '2'" label="CRON表达式:" prop="cron">
          <el-input v-model="form.cron" disabled clearable :maxlength="100" placeholder="请输入CRON表达式">
            <el-button slot="append" @click="$refs.vcrontabRef.showDialog()"> 生成表达式 </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="是否告警:" prop="isAlarm">
          <el-switch
            v-model="form.isAlarm"
            active-text="开"
            active-value="Y"
            active-color="#87D068"
            inactive-text="关"
            inactive-value="N"
            inactive-color="#D9001B"
          />
        </el-form-item>
        <div v-if="form.isAlarm == 'Y'">
          <el-form-item label="告警接收人:" prop="alarmUserId">
            <el-select v-model="form.alarmUserId" :multiple-limit="5" multiple clearable placeholder="请选择告警接收人">
              <el-option
                v-for="(item, index) in alarmUserIdList"
                :key="index"
                :label="item.realName + ' / ' + item.phone"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="告警方式:" prop="alarmType">
            <el-checkbox-group v-model="form.alarmType">
              <el-checkbox
                v-for="(item, index) in dictOptions.notificationMode"
                :key="index"
                :label="item.value"
              >
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!-- <el-form-item label="告警内容:" prop="alarmContent">
            <el-input v-model="form.alarmContent" type="textarea" :rows="3" clearable :maxlength="100" placeholder="推荐使用默认的告警内容，自定义可以查看使用手册中使用方式例如：${sceneName}场景在${date}执行报错，报错信息为${errorMsg}。" />
          </el-form-item> -->
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="!canClick" :loading="!canClick" @click="encryptDecryptConfirm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 生成CRON表达式 -->
    <dt-Vcrontab ref="vcrontabRef" v-model.trim="form.cron" />
  </div>
</template>

<script>
import { sceneAddApi, sceneGetDetailApi } from '@/api/serviceManage/serviceAdaptation'
import { getSystemListApi } from '@/api/serviceManage/requestPartyServiceManage'
import { getAlarmUserListApi } from '@/api/systemManage'
import dictMixin from '@/utils/mixins/dict'
export default {

  mixins: [
    dictMixin(['encryptMethod', 'executionMode@Local', 'notificationMode@Local'])
  ],

  props: {
    classifyTree: {
      type: Array,
      default: () => []
    }
  },

  data () {
    return {
      canClick: true,
      dialogVisible: false,
      form: {
        classifyParentIdPath: [],
        sceneName: '',
        executionMode: '',
        cron: '',
        isAlarm: '',
        requestSystemId: '',
        alarmUserId: [],
        alarmType: [],
        alarmContent: ''
      },
      formRules: {
        classifyParentIdPath: { required: true, message: '请选择关联分类', trigger: 'change' },
        sceneName: { required: true, message: '请输入场景名称', trigger: 'blur' },
        executionMode: { required: true, message: '请选择执行模式', trigger: 'change' },
        cron: { required: true, message: '请输入CRON表达式', trigger: 'change' },
        isAlarm: { required: true, message: '请选择是否告警', trigger: 'change' },
        requestSystemId: { required: false, message: '请选择系统', trigger: 'change' },
        alarmUserId: { required: true, message: '请选择告警接收人', trigger: 'change' },
        alarmType: { required: true, message: '请选择告警方式', trigger: 'change' }
      },
      checkList: [],
      // 系统列表
      requestSystemIdList: [],
      // 告警人列表
      alarmUserIdList: [],
      // 系统名称
      systemName: ''
    }
  },

  methods: {

    // 确定按钮
    encryptDecryptConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.canClick = false
          const params = this.$arrayStrInterchange(this.form, ['alarmType', 'alarmUserId'])
          params.classifyId = this.form.classifyParentIdPath.at([-1])
          delete params.classifyParentIdPath
          sceneAddApi({
            ...params
          }, this.form.id)
            .then(({ code, data }) => {
              if (code === '00000') {
                this.$message.success(this.form.id ? '修改成功' : '新建成功')
                this.dialogVisible = false
                this.$emit('refresh', data, this.form.requestSystemId)
              }
            }).finally(() => {
              this.canClick = true
            })
        }
      })
    },

    // 关联分类change
    classifyParentIdPathChange (val) {
      this.systemName = this.$refs['cascader'].getCheckedNodes()[0].data.systemName
      this.form.requestSystemId = this.$refs['cascader'].getCheckedNodes()[0].data.systemId
      this.requestSystemIdChange()
    },

    // 系统名称change
    requestSystemIdChange () {
      getAlarmUserListApi({
        systemId: this.form.requestSystemId
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.alarmUserIdList = data
        }
      })
    },

    // 获取各种初始数据
    async getInitData (data) {
      this.dialogVisible = true
      if (data) {
        sceneGetDetailApi({
          id: data.sceneId
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.form = this.$arrayStrInterchange({
              id: data.id,
              classifyParentIdPath: data.classifyParentIdPath.split(',').slice(1),
              sceneName: data.sceneName,
              executionMode: data.executionMode,
              cron: data.cron,
              isAlarm: data.isAlarm,
              requestSystemId: data.requestSystemId,
              alarmUserId: data.alarmUserId,
              alarmType: data.alarmType,
              alarmContent: data.alarmContent
            }, ['alarmType', 'alarmUserId'])
            this.systemName = data.requestSystemName
            this.requestSystemIdChange()
          }
        })
      } else {
        this.form = {
          classifyParentIdPath: [],
          sceneName: '',
          executionMode: '',
          cron: '',
          isAlarm: '',
          requestSystemId: '',
          alarmUserId: [],
          alarmType: [],
          alarmContent: ''
        }
        this.systemName = ''
        await this.$nextTick()
        this.$refs.form.resetFields()
      }

      // 获取系统
      getSystemListApi()
        .then(({ code, data }) => {
          if (code === '00000') {
            this.requestSystemIdList = data
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.scenario-configuration {
  ::v-deep .el-dialog__body {
    padding: 0 20px;
    max-height: 450px;
    overflow-y: auto;
  }
}

</style>
